import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

public class DynamicArray implements Iterable<Integer> {
    private int capacity = 8;//容量
    private int[] array = {};
    private int size = 0;//逻辑大小

    //向最后添加元素
    public void addLast(int element) {
        add(size, element);
    }

    //在指定位置添加元素
    public void add(int index, int element) {
        checkAndGrow();

        if (index >= 0 && index < size) {
            System.arraycopy(array, index, array, index + 1, (size - index));
        }
        array[index] = element;
        size++;
    }

    private void checkAndGrow() {
        if (size==0){
            array=new int[capacity];
        }
        //容量检查
        else if (size == capacity) {
            //扩容成1.5倍
            capacity += capacity >> 1;
            int[] newArray = new int[capacity];
            System.arraycopy(array, 0, newArray, 0, size);
            array = newArray;
        }
    }

    //获取index位置的元素
    public int get(int index) {
        return array[index];
    }

    //利用函数式接口:有且仅有一个抽象方法的接口叫做函数式接口，接口上可以加上@FunctionalInterface来校验
    public void forEach1(Consumer<Integer> consumer) {
        for (int i = 0; i < size; i++) {
            //这里可以给函数式接口提供array[i],具体实现在测试区
            consumer.accept(array[i]);
        }
    }

    //利用迭代器
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0;

            @Override
            public boolean hasNext() {
                return i < size;
            }

            @Override
            public Integer next() {
                return array[i++];
            }
        };
    }


    public IntStream stream() {
        return IntStream.of(Arrays.copyOfRange(array, 0, size));
    }

    //删除
    public int remove(int index) {
        int removed = array[index];
        if (index < size - 1) {
            System.arraycopy(array, index + 1, array, index, (size - index - 1));
        }
        size--;
        return removed;
    }

}
